#!/usr/bin/env python3
import re
from pathlib import Path

p = Path('config/protocols/monet/monet.md')
text = p.read_text(encoding='utf-8')
orig = text

# 1) Replace table header occurrences
text = text.replace(
    '| 地址 | 长度 | 描述 | 系数 | 范围 | bit | 备注 |',
    '| 地址 | 长度 | 描述 | 系数 | 范围 | bit | 数据类型 | 备注 |'
)

lines = text.splitlines()
new_lines = []
changed = 0
skipped = 0

for i,line in enumerate(lines):
    # skip markdown separator lines
    if re.search(r'^\|\s*-+\s*\|', line):
        new_lines.append(line)
        continue
    # count '|' to detect table rows with 7 columns (7 separators means 8 pipes)
    pipe_count = line.count('|')
    if pipe_count == 8 and line.strip().startswith('|'):
        # avoid header lines which we've changed already
        if '地址' in line and '描述' in line:
            new_lines.append(line)
            continue
        parts = line.split('|')
        # parts[1]..parts[7] are columns
        if len(parts) < 9:
            new_lines.append(line)
            continue
        addr = parts[1].strip()
        length = parts[2].strip()
        desc = parts[3].strip()
        coef = parts[4].strip()
        rng = parts[5].strip()
        bit = parts[6].strip()
        remark = parts[7].strip()

        dtype = ''
        remark_lower = remark
        # rule: high/low pair -> 32-bit
        if '高位' in desc or '低位' in desc:
            if 'HEX(有符号)' in remark:
                dtype = 'int32'
            else:
                dtype = 'uint32'
        else:
            # length numeric?
            try:
                ln = int(length)
            except:
                ln = None
            if ln == 4:
                if 'HEX(有符号)' in remark:
                    dtype = 'int32'
                else:
                    dtype = 'uint32'
            elif ln == 2:
                if 'HEX(有符号)' in remark:
                    dtype = 'int16'
                else:
                    # default unsigned
                    if 'HEX(无符号)' in remark:
                        dtype = 'uint16'
                    elif 'HEX' in remark:
                        # fallback
                        dtype = 'uint16'
                    else:
                        # if bit column present (not '-') maybe treat as uint16
                        if bit != '-' and bit != '':
                            dtype = 'uint16'
                        else:
                            dtype = ''
            else:
                # length is '-' or something else; if it's a bitmap (bit != '-') -> uint16
                if bit != '-' and bit != '':
                    dtype = 'uint16'
                else:
                    # if remark explicitly says HEX -> choose based on sign
                    if 'HEX(有符号)' in remark:
                        dtype = 'int16'
                    elif 'HEX(无符号)' in remark:
                        dtype = 'uint16'
                    else:
                        dtype = ''
        if dtype:
            # build new line with data type inserted before remark
            new_line = '|' + ' {} | {} | {} | {} | {} | {} | {} | {} |'.format(
                addr, length, desc, coef, rng, bit if bit!='' else '-', dtype, remark
            )
            new_lines.append(new_line)
            if new_line != line:
                changed += 1
        else:
            new_lines.append(line)
            skipped += 1
    else:
        new_lines.append(line)

new_text = '\n'.join(new_lines)
if new_text != orig:
    # backup
    backup = p.with_suffix('.md.bak')
    backup.write_text(orig, encoding='utf-8')
    p.write_text(new_text, encoding='utf-8')

print(f'Processed file: {p}');
print(f'Lines changed: {changed}, skipped: {skipped}');
if new_text != orig:
    print('Backup written to:', str(backup))
else:
    print('No changes were necessary.')
